from Bet.Bet365 import Bet365
from multiprocessing import Process, Lock, Queue
import time
from MailTool.Mail import Mail
import json
import traceback
import userConfig
from LoggingTool.Logging import Logging



class BetSpider(object):
    def __init__(self):
        # self.process = Process(target=self.matchesProcess, args=(20, ))
        self.bet365 = Bet365()
        self.bet365.login()
        Logging.info('登陆成功')

    def process(self):
        try:
            while True:
                self.bet365.login()

                print('matchesProcess is running..., and time is %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
                if self.bet365.hasFootball() == False:
                    print('matchesProcess has no football games')
                else:
                    if self.bet365.isSelectFootball():
                        if userConfig.isAsiaHalfItem == True:  #上半场比赛
                            if self.bet365.isAsiaHalf():
                                self.bet365.procHalfMatches()
                            else:
                                self.bet365.switchToAsiaHalf()
                        else:  #全场比赛
                            self.bet365.procFullMatches()
                    else:
                        self.bet365.switchToFootball()
                time.sleep(userConfig.SpiderInterval)
        except Exception as e:
            print('有异常抛出了哦！',e)
            time.sleep(userConfig.SpiderInterval)
            self.process()
        # finally:
            # time.sleep(userConfig.SpiderInterval)
    #
    # def matchesProcess(self, seconds):
    #     self.bet365 = Bet365()
    #     self.bet365.login()
    #     print('matchesProcess login sucess')
    #     Mail().send('登陆成功了', 'matchesProcess login sucess')
    #
    #     try:
    #         while True:
    #             print('matchesProcess is running..., and seconds is %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
    #             if self.bet365.hasFootball() == False:
    #                 print('matchesProcess has no football games')
    #                 time.sleep(seconds)
    #             else:
    #                 self.bet365.procMatches()
    #                 time.sleep(seconds)
    #     except Exception as e:
    #         print('有异常抛出了啊', json.dumps(traceback.format_exc()))
    #         Mail().send('抛出异常', json.dumps(traceback.format_exc()))



    def start(self):
        self.process()
        # self.process.daemon = True
        # self.process.start()
        # self.process.join()

        # self.p1.daemon = True
        # self.p2.daemon = True
        # self.p1.start()
        # self.p2.start()
        # self.p1.join()
        # self.p2.join()
